<template>
	<view class="page-body">
		<!-- 页面内容开始 -->
		<!-- 表格搜索组件开始 -->
		<vk-data-table-query
			v-model="queryForm1.formData"
			:columns="queryForm1.columns"
			size="mini"
			@search="search"
		></vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<view class="btns-box">
			<el-row>
				<el-radio-group v-model="queryForm1.formData.status" size="mini" @change="search">
					<el-badge :value="statusCountGroup[0] > 0 ? statusCountGroup[0] : ''" :max="999" class="group-badge">
						<el-radio-button :label="0">上架</el-radio-button>
					</el-badge>
					<el-badge :value="statusCountGroup[1] > 0 ? statusCountGroup[1] : ''" :max="999" class="group-badge">
						<el-radio-button :label="1">下架</el-radio-button>
					</el-badge>
					<!-- <el-badge :value="statusCountGroup[2] > 0 ? statusCountGroup[2] : ''" :max="999" class="group-badge">
						<el-radio-button :label="2">回收站</el-radio-button>
					</el-badge> -->
					<!-- 回收站内的数量不需要提示 -->
					<el-radio-button :label="2">回收站</el-radio-button>
					<el-badge :value="statusCountGroup[3] > 0 ? statusCountGroup[3] : ''" :max="999" class="group-badge">
						<el-radio-button :label="3">已售罄</el-radio-button>
					</el-badge>
				</el-radio-group>



				<!-- @click="addBtn" 之前的添加按钮的逻辑先注释掉 -->
				<el-button type="success" size="mini" icon="el-icon-circle-plus-outline" @click="addBtn" style="margin-left: 10px;">添加</el-button>
				<!-- 批量操作 -->
				<el-dropdown v-if="table1.multipleSelection" :split-button="false"	trigger="click" @command="batchBtn">
					<el-button type="danger" size="mini" style="margin-left: 20rpx;"
						:disabled="table1.multipleSelection.length === 0"
					>
						批量操作<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item :command="0">修改分类</el-dropdown-item>
						<el-dropdown-item :command="1">批量上架</el-dropdown-item>
						<el-dropdown-item :command="2">批量下架</el-dropdown-item>
						<el-dropdown-item :command="3">批量删除</el-dropdown-item>
						<el-dropdown-item :command="4">批量恢复</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
				<el-button @click="exportGoods" size="mini" style="margin-left: 10px;">导出商品</el-button>
				<el-button @click="importGoods" size="mini" style="margin-left: 10px;">导入商品</el-button>
			</el-row>
		</view>
		<!-- 自定义按钮区域结束 -->
		<el-container>
		  <el-aside width="125px" style="margin-top: 10px;">
				<el-tree
					:data="category.list"
					:props="category.props"
					:highlight-current="true"
					v-loading="category.loading"
					@node-click="categoryChange"
				></el-tree>
				<!-- <el-tabs tab-position="left" @tab-click="categoryChange" v-loading="category.loading">
					<el-tab-pane v-for="(item,index) in category.list" :key="item._id" :name="item._id">
						<view slot="label" :style="item.color ? 'color: '+item.color+';':''">
							<text>{{ item.name }}</text>
						</view>
					</el-tab-pane>
				</el-tabs> -->
			</el-aside>
		  <el-main style="padding: 0;">
				<!-- 表格组件开始 -->
				<vk-data-table
					ref="table1"
					:action="table1.action"
					:columns="table1.columns"
					:query-form-param="queryForm1"
					:right-btns="['detail_auto','update','more']"
					:custom-right-btns="[{
						title:'SKU',
						icon:'el-icon-shopping-cart-2',
						type:''
					}]"
					:right-btns-more="table1.rightBtnsMore"
					:selection="true"
					:row-no="false"
					:pagination="true"
					size="mini"
					@update="updateBtn"
					@delete="deleteBtn"
					@current-change="currentChange"
					@selection-change="selectionChange"
					@custom-right-btns="customRightBtns"
				>
					<!-- 排序值 -->
					<template v-slot:sort="{ row, column, index }">
						<el-input v-model="row.sort" size="mini" @change="sortChange($event, row)"/>
					</template>
					<!-- 库存 -->
					<template v-slot:stock="{ row, column, index }">
						<text>
							{{ stockFn(row.sku_list) }}
						</text>
						<vk-data-icon name="el-icon-edit" color="#409eff" bold pointer style="margin-left: 10px;" @click="vk.pubfn.openForm('updateStock',{ item:row });"></vk-data-icon>
					</template>
					<!-- sku价格区间 -->
					<template v-slot:sku_list="{ row, column, index }">
						<text>
							{{ priceRegionFn(row.sku_list) }}
						</text>
						<vk-data-icon name="el-icon-edit" color="#409eff" bold pointer style="margin-left: 10px;" @click="vk.pubfn.openForm('updatePrice',{ item:row });"></vk-data-icon>
					</template>
					<!-- 奖励规则 -->
					<template  v-slot:reward_rule="{ row, column, index }">
						<view>
							<text v-if="vk.getVuex('$user.mchInfo.fx.mode') == 'none'">未开启分销</text>
							<text v-else-if="$fn.getData(row,'reward_rule.is_custom') == 1" style="color: #1aad19;">独立规则</text>
							<text v-else-if="$fn.getData(row,'reward_rule.is_custom') == -1" style="color: #f56c6c;">无奖励</text>
							<text v-else>默认规则</text>
							<el-button v-if="vk.getVuex('$user.mchInfo.fx.mode') !== 'none'" @click="vk.pubfn.openForm('updateGoodsReward',{ item: row })" type="text" size="mini" style="margin-left: 6px;">设置</el-button>
						</view>
					</template>
				</vk-data-table>
				<!-- 表格组件结束 -->
			</el-main>
		</el-container>


		<!-- 详情页弹窗开始 -->
		<vk-data-dialog
			v-model="skuDetailDialog.show"
			width="1000px"
			top="14vh"
			center
			:close-on-click-modal="true"
		>
			<vk-data-detail-table
				:data="table1.selectItem"
				:columns="skuDetailDialog.columns"
			></vk-data-detail-table>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" size="medium" @click="skuDetailDialog.show=false">关 闭</el-button>
			</span>
		</vk-data-dialog>
		<!-- 详情页弹窗结束 -->

		<!-- 设置自定义会员价 -->
		<vipMoney v-model="formDatas.vipMoney" @success="refresh"></vipMoney>
		<!-- 修改商品库存 -->
		<updateStock v-model="formDatas.updateStock"></updateStock>
		<!-- 修改商品价格 -->
		<updatePrice v-model="formDatas.updatePrice"></updatePrice>
		<!-- 预览商品 -->
		<previewGoods v-model="formDatas.previewGoods"></previewGoods>
		<!-- 修改商品奖励规则 -->
		<updateGoodsReward v-model="formDatas.updateGoodsReward"></updateGoodsReward>
		<!-- 修改商品分类 -->
		<updateGoodsCategory v-model="formDatas.updateGoodsCategory" @success="refresh"></updateGoodsCategory>
		<!-- 导入商品 -->
		<importGoods v-model="formDatas.importGoods" @success="refresh"></importGoods>

		<!-- 页面内容结束 -->
	</view>
</template>

<script>
	var that;													// 当前页面对象
	var vk = uni.vk;									// vk实例
	var originalForms = {};						// 表单初始化数据

	const formatter_column_is = function(val, row, column, index) {
		let obj = {};
		if (val) {
			obj = {
				val: "是",
				tagType: "success"
			}
		}else{
			obj = {
				val: "否",
				tagType: "danger"
			}
		}
		return obj;
	};

	import vipMoney from './form/vipMoney'
	import updateStock from './form/updateStock'
	import updatePrice from './form/updatePrice'
	import previewGoods from './form/previewGoods'
	import updateGoodsReward from './form/updateGoodsReward'
	import updateGoodsCategory from './form/updateGoodsCategory'
	import importGoods from './form/importGoods'

	export default {
		components:{
			vipMoney,
			updateStock,
			updatePrice,
			previewGoods,
			updateGoodsReward,
			updateGoodsCategory,
			importGoods
		},
		data() {
			// 页面数据变量
			return {
				// 页面是否请求中或加载中
				loading:false,
				// 分组数据
				statusCountGroup:{

				},
				// 左侧订单状态切换数据
				category:{
					list:[

					],
					props:{
						children: 'children',
						label: 'name'
					},
					// 对应发货页面的逻辑
					countObj:{},
					loading:false,
				},
				data:{

				},
				// 表格相关开始 -----------------------------------------------------------
				table1:{
					// 表格数据请求地址
					action:"admin/business/sys.goods.getList",
					// 表格字段显示规则
					columns: [
						{ key:"sort", title:"排序", type:"number", width:80, defaultValue:'0', sortable:"custom" },
						{ key:"goods_thumb", title:"商品图", type:"avatar", imageWidth:40, shape:"square" },
						{ key:"name", title:"商品名称", type:"text", width:160, align:"left",
							maxlength:20,
							showWordLimit:true,
							buttonsPosition:"left", // 支持 left right bottom top
							buttons: [
								{
									title: "修改",
									type: "text", // 文字形式按钮 可选：primary / success / warning / danger / info / text
									mode: "update", // 模式 可选：update（通用修改模式） / default（自定义模式）
									show: ["row"], // 在哪些场景显示按钮 多选：row（在行内显示） / detail（在详情页显示）
									showRule: (formData) => {
										// 此为演示只有字段 key2 不等于 1时，才会显示此按钮。
										return (formData.key2 != 1) ? true : false;
									},
									click: (options) => {
										that.updateGoodsBaseInfo({
											data: options.formData,
											success: data => {
												// 通知组件操作成功（否则组件按钮会一直处于loading状态）
												options.success({
													msg: "修改成功"
												});
											}
										});
									}
								}
							]
						},
						{ key:"goods_desc", title:"商品描述", type:"text", width:160, defaultValue:'暂无', show:["detail"] },
						{ key:"categoryList", title:"所属分类", type:"text", width:140, defaultValue:'暂无',
							formatter: (val, row, column, index) => {
								let str = "";
								val.map((item, index) => {
									if (index > 0) str += "、";
									str += item.name;
								});
								return str;
							}
						},
						{ key:"sku_list", title:"价格区间", type:"text", width:200, defaultValue:'暂无' ,
							formatter:(val, row, column, index) => {
								let a = [];
								val.map((item, index) => {
									a.push(Number(item.price))
								});
								let max = Math.max(...a);
								let min = Math.min(...a);
								if(max != min){
									// 如果最大值和最小值不相等
								  return	vk.pubfn.priceFilter(min) +' - '+ vk.pubfn.priceFilter(max);
								}else{
									// 如果最大值和最小值相等
									return  vk.pubfn.priceFilter(min);
								}
							}
						},
						{ key: "stock", title: "商品库存", type: "number", width: 130, show:["row"]  },
						{
						  key: "type", title: "商品类别", type: "radio", width: 90, defaultValue:0,
						  data:[
						    { value:0, label:"实物商品" },
						    { value:1, label:"电子卡券" },
						  ]
						},
						{ key:"is_on_sale", title:"是否上架", type:"switch", width:80,
							watch:(res)=>{
								let { value, row, change } = res;
								vk.callFunction({
									url: "admin/business/sys.goods.updateIsOnSale",
									title: value ? "上架中..." : "下架中...",
									data: {
										ids: [row._id],
										is_on_sale: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},
						{ key:"reward_rule", title:"分销奖励规则", type:"text", width:120, show:["row"]  },
						{ key:"keywords", title:"商品关键字", type:"text", width:100, defaultValue:'暂无'},
						{ key:"view_count", title:"累计浏览量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"total_sell_count", title:"显示总销量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"initial_sell_count", title:"初始总销量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"real_sell_count", title:"实际总销量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"comment_count", title:"累计评价数", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"on_sale_time", title:"上架时间", type:"time", width:160 },

						{
							key: "is_best", title:"是否精品", type:"switch", activeValue:true, inactiveValue:false, width:80,
							watch: (res) => {
								let { value, row, column, change } = res;
								that.updateGoodsBaseInfo({
									data: {
										_id: row._id,
										[column.key]: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},
						{
							key: "is_new", title:"是否新品", type:"switch", activeValue:true, inactiveValue:false, width:80,
							watch: (res) => {
								let { value, row, column, change } = res;
								that.updateGoodsBaseInfo({
									data: {
										_id: row._id,
										[column.key]: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},
						{
							key: "is_hot", title:"是否热销", type:"switch", activeValue:true, inactiveValue:false, width:80,
							watch: (res) => {
								let { value, row, column, change } = res;
								that.updateGoodsBaseInfo({
									data: {
										_id: row._id,
										[column.key]: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},
						{
							key: "disable_vip", title:"是否禁用会员价", type:"switch", activeValue:true, inactiveValue:false, width:130, activeColor:"#ff4949", inactiveColor:"#13ce66", activeText:"禁", inactiveText:"可",
							watch: (res) => {
								let { value, row, column, change } = res;
								that.updateGoodsBaseInfo({
									data: {
										_id: row._id,
										[column.key]: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},
						{
							key: "disable_coupon", title:"是否禁用优惠券", type:"switch", activeValue:true, inactiveValue:false, width:130, activeColor:"#ff4949", inactiveColor:"#13ce66", activeText:"禁", inactiveText:"可",
							watch: (res) => {
								let { value, row, column, change } = res;
								that.updateGoodsBaseInfo({
									data: {
										_id: row._id,
										[column.key]: value
									},
									success: data => {
										change(value);
									}
								});
							}
						},

						{ key:"seller_note", title:"商家备注,仅商家可见", type:"text", width:160, defaultValue:'暂无' },
						{ key:"_add_time",title:"创建时间", type:"time", width:180 },
						{ key:"update_time", title:"修改时间", type:"dateDiff", width:160, defaultValue:'无' },
						{ key:"_id", title:"商品ID", type:"text", width:210 },
						{ key:"goods_banner_imgs", title:"商品轮播图", type:"image", width:200, show:["detail"] },
						{
							key:"goods_detail_mode", title:"展示方式", type:"radio", show:["detail"],
							data:[
								{ value:0, label:"简易模式（纯图片）" },
								{ value:1, label:"富文本模式（图片+文字）" }
							],
						},
						{ key:"goods_detail_imgs", title:"简易模式图片", type:"image", width:200, show:["detail"] },
						{ key:"goods_detail_body", title:"富文本模式详情", type:"html", width:360, show:["detail"] },
					],
					// 多选框选中的值
					multipleSelection:[],
					// 当前高亮的记录
					selectItem:"",
					rightBtnsMore:[
						{
							title: '预览',
							onClick: (item)=>{
								let h5Config = vk.getVuex('$user.mchInfo.h5') || {};
								let { domain,path } = h5Config;
								if (!domain) {
									this.$confirm('请先前往平台管理-h5，设置服务域名', '提示', {
										confirmButtonText: '立即前往',
										cancelButtonText: '取消',
										type: 'warning'
									}).then(() => {
										vk.navigateTo("/pages/app-platform/h5");
									}).catch(() => {

									});
									return;
								}
								let rootPath;
								if (path) {
									rootPath = `${domain}/${path}`;
								} else {
									rootPath = domain;
								}
								let pagePath = `/pages/goods/goods-detail?_id=${item._id}`;
								let url = rootPath + pagePath;
								vk.pubfn.openForm('previewGoods', { url });
							}
						},
						{
							title: '查看评价',
							onClick: (item)=>{
								vk.navigateTo(`./comment/list?_id=${item._id}`);
							}
						},
						{
							title: '查看订单',
							onClick: (item)=>{
								vk.navigateTo(`/pages/order/list?goods_id=${item._id}`);
							}
						},
						{
							title: '独立会员价',
							onClick: (item)=>{
								vk.pubfn.openForm('vipMoney', { item });
							}
						},
						{
							title: '复制创建',
							onClick: (item)=>{
								that.copyNewGoods(item);
							}
						},
						{
							title: '删除',
							onClick: (item)=>{
								that.deleteGoods(item._id);
							},
							show: (item) => {
								return [0,1,2].indexOf(item.status) > -1;
							}
						}
					]
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1:{
					// 查询表单数据源，可在此设置默认值
					formData:{
						status:0,
						name:"",
						_add_time:[],
						category_ids:""
					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns:[
						{ key: "name", type: "text", title:"", placeholder:"请输入商品名称", width:220, mode:"%%"  },
						{ key: "_add_time", type: "datetimerange", title:"添加时间" ,width:320, mode:"[]"  },
						{ key: "category_ids", type: "text", title:"分类" ,width:320, mode:"in", show:false },
					]
				},
				// 表单相关结束-----------------------------------------------------------
				// sku详情弹窗
				skuDetailDialog:{
					show:false,
					columns:[
						{ key:"spec_list", title:"规格组列表", type:"table", width:160, defaultValue:'暂无', show:["detail"],
							columns:[
								{ key:"name", title:"规格名", type:"tag", width:100, size: "medium",
									formatter: function(val, row, column, index) {
										return {
											val: val,
											tagType: ""
										};
									}
								},
								{ key:"list", title:"规格值", type:"html", minWidth:100, align:"left",
									formatter: function(val=[], row, column, index) {
										let str = "";
										for(let i=0;i<val.length;i++){
											str += `<span class="el-tag el-tag--medium el-tag--plain">${val[i].name}</span>`;
											if(i<(val.length-1)){
												str += " ";
											}
										}
										return str;
									}
								},
							]
						},
						{ key:"sku_list", title:"sku列表", type:"table", width:160, show:["detail"],
							// rowHeight:56,
							columns:[
								{ key:"image", title:"商品图片", type:"avatar", width:100 },
								{ key:"sku_name", title:"SKU名称", type:"text", minWidth:100 },
								{ key:"price", title:"价格", type:"money", width:100 },
								{ key:"market_price", title:"市场价", type:"money", width:100, defaultValue:"未设置" },
								{ key:"stock", title:"库存", type:"number", width:100, defaultValue:0 },
								{ key:"weight", title:"重量", type:"number", width:100, defaultValue:0 },
								{ key:"real_sell_count", title:"销量", type:"number", width:100, defaultValue:0 },
								//{ key:"vip_price_rules", title:"单独会员价规则", type:"text", width:150, defaultValue:'无' },
							]
						},
					]
				},
				// 表单弹窗数据源
				formDatas:{},
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				if(options.msg){
					setTimeout(()=>{
					that.$notify({
						message:'操作成功!',
						type:'success'
					})
					},100);
				}
				that.getCategory();
				that.getStatusCountGroup();
			},
			getStatusCountGroup(){
				vk.callFunction({
					url: 'admin/business/sys.goods.getStatusCountGroup',
					data: {

					},
					success: (data) => {
						that.statusCountGroup = data.group;
					}
				});
			},
			getCategory(){
				vk.callFunction({
					url: 'admin/business/sys.goodsCategory.kh_getList',
					loading: { name:"category.loading", that },
					data: {

					},
					success: (data) => {
						data.rows.unshift({
							_id:"",
							name:"全部"
						});
						that.category.list = data.rows;
					}
				});
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 搜索
			search(obj){
				that.$refs.table1.query(obj);
				that.getStatusCountGroup();
			},
			// 刷新
			refresh(){
				that.$refs.table1.refresh();
				that.getStatusCountGroup();
			},
			// 获取当前选中的行的数据
			getCurrentRow(key){
				return that.$refs.table1.getCurrentRow(key);
			},
			// 监听 - 行的选中高亮事件
			currentChange(val){
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 显示添加页面
			addBtn(){
				vk.navigateTo({
					url: "./edit?mode=add",
					events: {
						add: (data) => {
							that.refresh();
						}
					}
				})
			},
			// 显示修改页面
			updateBtn({ item, row }){
				vk.navigateTo({
					url: `./edit?mode=update&_id=${row._id}`,
					events: {
						update: (data) => {
							vk.pubfn.objectAssign(row, data);
						}
					}
				})
			},
			// 删除按钮
			deleteBtn({ item, deleteFn }){
				deleteFn({
					action:"admin/business/sys.goods.delete",
					data:{
						_id: item._id
					},
				});
			},
			// 监听 - 批量操作的按钮点击事件
			batchBtn(index){
				switch(index){
					case 0: that.updateCategory(); break;
					case 1: that.updateIsOnSale(true); break;
					case 2: that.updateIsOnSale(false); break;
					case 3: that.deleteGoods(); break;
					case 4: that.recoveryGoods(); break;
					default : break;
				}
			},
			customRightBtns(row ,btn){
				if(btn.title === "SKU"){
					that.skuDetailDialog.show = true;
				}
			},
			copyNewGoods(item){  //复制创建
			  that.$message({
					message:'复制成功,将为您打开添加页面!',
					type:'success',
					duration:600
				});
				setTimeout(()=>{
					vk.navigateTo({
						url: `./edit?mode=add&_id=${item._id}`,
						events: {
							add: (data) => {
								that.refresh();
							}
						}
					})
				},600);
			},
			// 修改分类
			updateCategory(){
				let goods_ids = [];
				that.table1.multipleSelection.map((item, index) => {
					goods_ids.push(item._id);
				});
				vk.pubfn.openForm('updateGoodsCategory',{ goods_ids });
			},
			// 批量删除
			deleteGoods(ids){
				let data = {
					mode: that.queryForm1.formData.status === 2 ? 2 : 1
				};
				if (vk.pubfn.isNull(ids)) {
					ids = vk.pubfn.arrayObjectGetArray(that.table1.multipleSelection,"_id");
				}

				if (vk.pubfn.isArray(ids)) {
					data["ids"] = ids;
				} else {
					data["ids"] = [ids];
				}

				vk.callFunction({
					url: 'admin/business/sys.goods.delete',
					title:'请求中...',
					data,
					success:function(data){
						that.refresh();
					}
				});
			},
			recoveryGoods(){
				let ids = vk.pubfn.arrayObjectGetArray(that.table1.multipleSelection,"_id");
				vk.callFunction({
					url: 'admin/business/sys.goods.recovery',
					title:'请求中...',
					data:{
						ids,
					},
					success:function(data){
						that.refresh();
					}
				});
			},
			// 批量上下架
			updateIsOnSale(is_on_sale){
				let ids = vk.pubfn.arrayObjectGetArray(that.table1.multipleSelection,"_id");
				vk.callFunction({
					url: 'admin/business/sys.goods.updateIsOnSale',
					title:'请求中...',
					data:{
						ids,
						is_on_sale
					},
					success:function(data){
						that.refresh();
					}
				});
			},
			categoryChange(item){
				that.queryForm1.formData.category_ids = item._id;
				that.search();
			},
			sortChange(sort, item){
				vk.callFunction({
					url: 'admin/business/sys.goods.updateGoodsSort',
					data: {
						_id: item._id,
						sort: Number(sort)
					},
					success: (data) => {

					}
				});
			},
			updateGoodsBaseInfo(obj){
				vk.callFunction({
					url: "admin/business/sys.goods.updateGoodsBaseInfo",
					title: "请求中...",
					...obj
				});
			},
			stockFn(value){
				let allStock = 0;
				value.map((item, index) => {
					allStock += parseInt(item.stock);
				});
				return parseInt(allStock);
			},
			priceRegionFn(value){
				let a = [];
				value.map((item, index) => {
					a.push(Number(item.price))
				});
				let max = Math.max(...a);
				let min = Math.min(...a);
				if(max != min){
					// 如果最大值和最小值不相等
				  return	vk.pubfn.priceFilter(min) +' - '+ vk.pubfn.priceFilter(max);
				}else{
					// 如果最大值和最小值相等
					return  vk.pubfn.priceFilter(min);
				}
			},
			// 导出商品
			exportGoods(){
				let isTrue = [
					{ value:true, label:"是" },
					{ value:false, label:"否" }
				];
				let arraryFormatter = (val, row, column, index)=>{
					let str = "";
					val.map((item, index) => {
						str += `${item}`;
						if (val.length-1 != index) {
							str += `,`;
						}
					});
					return str;
				}
				this.$refs.table1.exportExcel({
				  fileName: "商品数据",
				  title: "正在导出数据...",
					pageIndex: 1,
					pageSize: -1, // 此值为-1，代表导出所有数据
					columns: [
						{ key:"sort", title:"排序", type:"number" },
						{
							key:"is_on_sale", title:"销售状态", type:"radio",
							data:[
								{ value:true, label:"上架" },
								{ value:false, label:"下架" }
							]
						},
						{
							key:"type", title:"商品类型", type:"radio",
							data:[
								{ value:0, label:"实物" },
								{ value:1, label:"虚拟" }
							]
						},
						{ key:"name", title:"商品名称", type:"text" },
						{ key:"categoryList", title:"所属分类", type:"text",
							formatter: (val, row, column, index) => {
								let str = "";
								val.map((item, index) => {
									if (index > 0) str += ",";
									str += item.name;
								});
								return str;
							}
						},
						{ key:"goods_desc", title:"商品描述", type:"text" },
						{ key:"goods_thumb", title:"商品图片链接", type:"text" },
						{ key:"goods_banner_imgs", title:"商品轮播图链接", type:"text", formatter: arraryFormatter },
						{ key:"goods_detail_imgs", title:"商品详情页图片链接", type:"text", formatter: arraryFormatter },
						{ key:"goods_services", title:"服务标签", type:"text", formatter: arraryFormatter },
						{ key:"is_free_delivery", title:"是否包邮", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"freight_id", title:"运费id", type:"text" },
						{
							key:"spec_list", title:"规格信息", type:"text",
							formatter: (val=[], row, column, index) => {
								let str = "";
								val.map((item, index) => {
									str += `${item.name}:`
									item.list.map((item2, index2) => {
										str += `${item2.name}`
										if (item.list.length-1 !== index2) {
											str += `,`
										}
									});
									if (val.length-1 !== index) {
										str += `;`
									}
								});
								return str;
							}
						},
						{
							key:"sku_list", title:"具体规格", type:"text",
							formatter: (val=[], row, column, index) => {
								let str = "";
								val.map((item, index) => {
									let skuName = "";
									item.sku_name_arr.map((nameItem, nameIndex) => {
										skuName += nameItem;
										if (item.sku_name_arr.length-1 !== nameIndex) skuName += `,`
									});
									let price = vk.pubfn.toDecimal(item.price/100, 2);
									let market_price = 0;
									if (item.market_price) {
										market_price = vk.pubfn.toDecimal(item.market_price/100, 2);
									}
									// 规格值:售价,市场价,库存,重量,图片;
									str += `${skuName}::${price},${market_price},${item.stock},${item.weight},${item.image}`;
									if (val.length-1 !== index) {
										str += `;`
									}
								});
								return str;
							}
						},
						{ key:"is_new", title:"是否新品", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"is_best", title:"是否精品", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"is_hot", title:"是否热销", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"disable_vip", title:"是否禁用会员价", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"disable_coupon", title:"是否禁用优惠券", type:"radio", data:isTrue, defaultValue:"否" },
						{ key:"initial_sell_count", title:"商品初始销量", type:"text" },
						{ key:"exp_time_mode", title:"虚拟商品有效期模式", type:"number",
							formatter: (val, row, column, index) => {
								if (row.type == 0) return "";
								return val
							}
						},
						{
							key:"exp_time_range", title:"虚拟商品有效期", type:"text",
							formatter: (val, row, column, index) => {
								if (row.type == 0) return "";
								if (row.exp_time_mode === 0) return "长期有效";
								if (row.exp_time_mode === 1) return `${row.exp_time_range[0]}-${row.exp_time_range[1]}`;
								if (row.exp_time_mode === 2) return `${row.exp_time_rule[0]}-${row.exp_time_rule[1]}`;
							}
						}
					]
				});
			},
			// 导入商品
			importGoods(){
				vk.pubfn.openForm('importGoods', { item:{} });
			}
		},
		watch: {

		},
		// 计算属性
		computed: {

		}
	};
</script>
<style lang="scss" scoped>
	.page-body {
		.sort-input{
			font-size: 12px;
		}
		::v-deep .el-tree-node__content{
			height: 40px;
			font-weight: 600;
		}
		.group-badge{
			::v-deep .el-badge__content.is-fixed{
				z-index: 2;
				right: 20px;
				text-align: right;
			}
		}
	}
</style>
